#pragma once

#include <iostream>

template<typename T>
class List
{
public:
	List();
	~List();

	void ShowData();

	int Capacity() const;
	int Size() const;

	void Insert(int index, T element);
	void Remove(int index);
	T& operator[](int index);
private:
	int capacity;
	int size;
	T* data;
};


template <typename T>
List<T>::List():
	capacity(10),
	size(0)
{
	data = new T[capacity];
}

template <typename T>
List<T>::~List()
{
	delete[] data;
}

template <typename T>
void List<T>::ShowData()
{
	std::cout << "Show List: \n";
	std::cout << "Capacity: " << capacity << "\n";
	std::cout << "Size: " << size << "\n";
	
	for (int i = 0; i < size; ++i)
	{
		std::cout << data[i] << " ";
	}
	std::cout << std::endl;
}

template <typename T>
int List<T>::Capacity() const
{
	return capacity;
}

template <typename T>
int List<T>::Size() const
{
	return size;
}

template <typename T>
void List<T>::Insert(int index, T element)
{
	if (index < 0 || index > size)
		return;

	// 扩容检查
	if (size == capacity)
	{
		// capacity 扩大为原来的2倍
		capacity *= 2;
		// 申请新内存
		T* newData = new T[capacity];
		// 将原数据转移到新内存中
		for (int i = 0; i < size; ++i)
			newData[i] = data[i];
		// 释放原来的内存
		delete[] data;
		data = newData;
	}
	
	// 将当前索引及之后的元素往后移一位
	for (int i = size; i > index; --i)
	{
		data[i] = data[i - 1];
	}
	data[index] = element;

	++size; 
}

template <typename T>
void List<T>::Remove(int index)
{
	if (index < 0 || index > size)
		return;

	// 将当前索引及之后的元素往前移一位
	for (int i = index; i < size; ++i)
	{
		data[i] = data[i + 1];
	}

	--size; 
}

template <typename T>
T& List<T>::operator[](int index)
{
	return data[index];
}
